// 与数据库打交道
const {
  create,
  del,
  list,
  count,
  get,
  getByName,
  systems,
} = require('../../../model/owner')

const {
  Success,
  SysErr,
  OwnerNameExistsErr,
} = require('../../../response/code')
const { md5 } = require('../../../util/crypt')
const { randStr } = require('../../../util/random')

class OwnerService {
  async create(ctx) {
    try {
      const data = ctx.request.body

      // 判断owner是否存在
      const exists = await getByName(data.name, { deleted_at: null })
      if (exists) {
        return ctx.app.emit('error', OwnerNameExistsErr, ctx)
      }
      data.enabled = true
      data.code = md5(randStr(32) + new Date().getMilliseconds())

      const result = await create(data)
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async get(ctx) {
    try {
      const query = ctx.request.query
      const result = await get(query.id)
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async del(ctx) {
    try {
      const body = ctx.request.body
      // 存在则删除
      const result = await del(body.id, {
        deleted_at: null,
      })
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async systems(ctx) {
    try {
      const result = await systems()
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async list(ctx) {
    try {
      const query = ctx.request.query
      const where = {
        deleted_at: null,
      }
      const data = await list(query.pageNo, query.pageSize, where) // 可以添加第三个参数条件过滤
      const total = await count(where)
      const result = {
        list: data,
        count: total,
      }
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }
}
module.exports = new OwnerService()
